package com.guigu.servicegoods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.common_util.pojo.config.CacheKey;
import com.guigu.common_util.pojo.utils.Result;
import com.guigu.servicegoods.domain.TbCategory;
import com.guigu.servicegoods.domain.TbSpec;
import com.guigu.servicegoods.mapper.TbSpecMapper;
import com.guigu.servicegoods.service.TbCategoryService;
import com.guigu.servicegoods.service.TbSpecService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@Service
public class TbSpecServiceImpl extends ServiceImpl<TbSpecMapper, TbSpec> implements TbSpecService {

    @Autowired
    private TbCategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TbSpecMapper specMapper;

    @Override
    public Result findPage(Map<String, Object> searchMap, Integer page, Integer size) {
        QueryWrapper<TbSpec> wrapper = createExample(searchMap);
        Page<TbSpec> pageSpec = new Page<>(page,size);
        baseMapper.selectPage(pageSpec,wrapper);
        return Result.ok().data("row",pageSpec.getRecords()).data("total",pageSpec.getTotal());
    }

//    @Scheduled(cron = "0 0 2 * * ?")
    @Scheduled(fixedRate = 86400000)
    @Override
    public void findListByCategoryName() {
        List<TbCategory> categoryList = categoryService.list(null);
        for (TbCategory category:categoryList) {
            List<Map> specList = specMapper.findListByCategoryName(category.getName());
            redisTemplate.boundHashOps(CacheKey.CATEGORY_SPEC).put(category.getName(),specList);
        }
        System.out.println("执行了定时任务spec");
    }

    // 根据查询条件封装模块对象
    private QueryWrapper<TbSpec> createExample(Map<String, Object> searchMap) {
        QueryWrapper<TbSpec> wrapper = new QueryWrapper<>();
        if(searchMap!=null) {
            if(searchMap.get("id")!=null)
                wrapper.eq("id",searchMap.get("id"));
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name")))
                wrapper.like("name",searchMap.get("name"));
            if(searchMap.get("templateId")!=null)
                wrapper.eq("template_id",searchMap.get("templateId"));
        }
        return wrapper;
    }
}
